import React, { useEffect } from 'react'
import { Form, Modal, message } from 'antd'
import { BetaSchemaForm, } from '@ant-design/pro-components'
import { createUserFormColumns } from '../constant'
import { createUserApi, updateUserApi } from '../../../services'
import type { CreateUserParams, UserItem } from '../../../types/services'

interface Props {
  editRowInfo: UserItem | null
  visible: boolean
  setVisible: (visible: boolean) => void
  refresh: () => void
}

const CreateUserModal: React.FC<Props> = (props) => {
  const [form] = Form.useForm()

  useEffect(() => {
    // 如果是编辑就反显数据
    if (props.editRowInfo) {
      form.setFieldsValue({ ...props.editRowInfo })
    }
  }, [props.editRowInfo])

  useEffect(() => {
    // 关闭弹窗时重置表单
    if (!props.visible) {
      form.resetFields()
    }
  }, [props.visible])

  const createUser = async (value: CreateUserParams) => {
    const res = await createUserApi(value)
    if (res.data.code === 200) {
      props.setVisible(false)
      message.success('创建成功')
      props.refresh()
    } else {
      message.error(res.data.msg)
    }
  }
  const updateUser = async (value: CreateUserParams) => {
    // 调用更新接口
    const res = await updateUserApi({...value, id: props.editRowInfo!._id})
    if (res.data.code === 200) {
      props.setVisible(false)
      message.success('更新成功')
      props.refresh()
    } else {
      message.error(res.data.msg)
    }
  }

  return (
    <Modal
      title={props.editRowInfo ? '编辑用户' : '创建用户'}
      open={props.visible}
      onOk={() => form.submit()}
      onCancel={() => props.setVisible(false)}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        onFinish={async (value: CreateUserParams) => {
          if (props.editRowInfo) {
            updateUser(value)
          } else {
            createUser(value)
          }
        }}
      >
        <BetaSchemaForm<CreateUserParams>
          layoutType="Embed"
          columns={createUserFormColumns}
        />
      </Form>
    </Modal>
  )
}

export default CreateUserModal